<template>
  <link
    rel="stylesheet"
    href="https://at.alicdn.com/t/c/font_4682916_eus4j1hjo3.css"
  />
  <div class="box">
    <h2>todos</h2>
    <div class="header">
      <input type="text" @keyup.enter="addTodo" placeholder="请输入你的任务" />
    </div>
    <div>
      <ul>
        <li v-for="(item, index) in todos" :key="item.id">
          <div>
            <input type="checkbox" v-model="item.isDone" />
            <span :class="[item.isDone ? 'line' : '']">{{ item.name }}</span>
          </div>
          <div
            @click="delTodo(index)"
            class="iconfont icon-a-11-Xhao01 a"
          ></div>
        </li>
      </ul>
      <div class="footer" v-if="todos.length !== 0">
        <span>{{ unTodoCount }}项未完成</span>
        <div>
          <span @click="clearTodo">清除已完成</span>
          <span @click="checkAll">全选</span>
        </div>
      </div>
      <h2 v-else>暂无任务</h2>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch, onMounted } from "vue";
const todos = ref([]);

onMounted(() => {
  todos.value = JSON.parse(
    localStorage.getItem("todos") ? localStorage.getItem("todos") : "[]"
  );
});

watch(
  todos,
  () => {
    localStorage.setItem("todos", JSON.stringify(todos.value));
  },
  { deep: true }
);

// 添加
const addTodo = (event) => {
  // event.target：获取事件发生的目标元素
  let name = event.target.value.trim();
  if (!name) {
    alert("你还没有输入任务");
    return;
  }
  let todo = { id: Date.now(), name, isDone: false };
  todos.value.unshift(todo);
  event.target.value = "";
};

// 删除todo
const delTodo = (index) => {
  if (confirm("确认删除吗?")) {
    todos.value.splice(index, 1);
  }
};

// 全选
let isAll = false;
const checkAll = () => {
  isAll = !isAll;
  todos.value.forEach((item) => {
    item.isDone = isAll;
  });
};

// 清除已完成
const clearTodo = () => {
  todos.value = todos.value.filter((item) => !item.isDone);
};

// 计算未完成的todo数量
const unTodoCount = computed(() => {
  return todos.value.filter((item) => !item.isDone).length;
});
</script>

<style  scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-size: 20px;
}
.iconfont {
  font-size: 25px;
}
.box {
  width: 320px;
  margin: 50px auto;
}
.box h2 {
  text-align: center;
}
.box h2:last-child {
  color: red;
}
.header input {
  width: 100%;
}
ul li {
  margin-top: 10px;
  list-style-type: none;
  display: flex;
  justify-content: space-between;
  align-content: center;
}
ul li input {
  margin-right: 15px;
  width: 18px;
  height: 18px;
}
ul li div:last-child {
  color: red;
  cursor: pointer;
}
.line {
  text-decoration: line-through;
  color: grey;
}

.footer {
  display: flex;
  justify-content: space-between;
  align-content: center;
  cursor: pointer;
}
.footer div span:last-child {
  margin-left: 10px;
}
</style>